﻿using EfCore.Core;
using EfCore.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace EfCore.Web.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationContext _ctx;
        public HomeController(ApplicationContext ctx)
        {
            _ctx = ctx;
        }
        public async Task<IActionResult> Index()
        {
            #region Obsolete.
            //await _ctx.AddAsync(new Province()
            //{
            //    Name = "江苏省",
            //    Population = 10000,
            //    Cities = new List<City>()
            //    {
            //        new City(){
            //             Name="南京市",
            //              AreaCode="001",
            //               CityCompanies=new List<CityCompany>(){
            //                    new CityCompany(){
            //                         Company=new Company()
            //                         {
            //                              Name="江苏省南京市凤凰新华电商中心"
            //                         }
            //                    }
            //               }
            //        }
            //    }
            //});
            //await _ctx.SaveChangesAsync();
            //var para = "南京市";
            //var para = "%江苏%";
            //var list = await _ctx.Province.AsNoTracking().Where(p=>p.Name.Contains(para)).ToListAsync();
            //var list = await _ctx.Province.AsNoTracking()
            //    .Where(p => EF.Functions.Like(p.Name, para))
            //    .ToListAsync();

            #endregion

            var list = await _ctx.Province.AsNoTracking()
                .Include(p => p.Cities)
                .ToListAsync();

            #region Obsolete.
            //List<dynamic> list = await _ctx.Province.Select(p => new
            //{
            //    ProvinceName = p.Name,
            //    Cities = p.Cities
            //}).ToListAsync<dynamic>();
            //foreach (var item in list)
            //{
            //    Console.WriteLine(item.ProvinceName);
            //} 

            //var province = await _ctx.Province.FirstOrDefaultAsync();
            //province.Name = "浙江省";
            //_ctx.Entry(province).State = EntityState.Modified;
            //await _ctx.SaveChangesAsync();
            #endregion

            return View(list);
        }
    }
}
